<template>
  <div class="realTime">
    <el-checkbox-group v-model="dRecordIds">
      <el-checkbox v-for="item in flightList" :key="item.value" :value="item.value" class="flight-item"
        @click="handleFlightChange(item)">
        <div class="flight-content">
          <div class="flight-id">{{ item.label }}</div>
          <div class="flight-info">
            <span>{{ item.time || "暂无时间" }}</span>
          </div>
          <div class="flight-tag">飞行中</div>
        </div>
      </el-checkbox>
    </el-checkbox-group>

    <div v-if="flightList.length === 0" class="empty-state">
      <i class="el-icon-warning-outline"></i>
      <span>暂无架次数据</span>
    </div>
  </div>
</template>

<script setup>
import { getAssets } from "@/utils/index.ts";
import mapStore from "@/stores/modules/map.ts";
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { eventBus } from "@/components/cme-base2D/core/EventBus";
import { getHistoryFlights, getActualTime } from "@/api/planeReplayData/index.ts";
import moment from 'moment'
import { mapApi } from "../../../components/cme-mapboxCore/api/mapApi";

const mapStores = mapStore()

const dRecordIds = ref([]) // 选中的架次ID列表
const flightList = ref([]) // 架次列表
const timers = ref([]) // 定时器列表
const timerMap = ref(new Map()) // 定时器映射表
const activeFlightData = ref([]) // 活动架次数据
const trajectoryLoading = ref(false) // 轨迹加载状态
const eventSource = ref(null) // SSE事件源
const selectedFlights = ref([]) // 已选择的架次

/**
 * 计算过滤后的架次列表
 */
const filteredFlightList = computed(() => {
  if (!searchText.value) return flightList.value
  return flightList.value.filter(flight =>
    flight.label.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

/**
 * 格式化时间戳
 * @param {number} timestamp 时间戳
 * @returns {string} 格式化后的时间字符串
 */
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  return moment(timestamp).format('YY-MM-DD HH:mm:ss')
}

/**
 * 获取今日架次数据
 */
const getTodaysFlights = async () => {
  try {
    const res = await getHistoryFlights()
    if (res.code === 200) {
      flightList.value = res.data.map(items => {
        return {
          value: items.flight,
          label: items.flight,
          time: moment(items.epoch).format('YYYY-MM-DD HH:mm:ss')
        }
      })
      // mapApi.modelMove.realTimeLoadModel(flightList.value.map(items => ({ id: items.value, coordinates: [0, 0, 0], bearing: 0 })))
    }

  } catch (error) {
    ElMessage.error('获取架次数据失败')
    console.error('获取架次数据失败:', error)
  }
}

/**
 * 关闭SSE连接
 */
const eventSourceClose = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
}

/**
 * 处理架次选择变更
 */
const handleFlightChange = async (flight) => {
  const isSelected = dRecordIds.value.includes(flight.value)
  isSelected ? await handleFlightDeselect(flight) : await handleFlightSelect(flight)
}

/**
 * 处理取消选择架次
 */
const handleFlightDeselect = async (flight) => {
  selectedFlights.value = selectedFlights.value.filter(id => id !== flight.value)
  eventSourceClose()
  // 清除轨迹
  mapApi.modelMove.removeRealModel(flight.value)
}

/**
 * 处理选择架次
 */
const handleFlightSelect = (flight) => {
  selectedFlights.value.push(flight.value)
  getWithTrajectory(selectedFlights.value.join(','))
}

/**
 * 获取架次轨迹数据
 * @param {string} id 架次ID
 * @param {boolean} showFullScreen 是否显示全屏加载
 */
const getWithTrajectory = async (id, showFullScreen = true) => {
  const loadingInstance = showFullScreen ? ElLoading.service({
    lock: true,
    text: '正在加载轨迹数据...',
    background: 'rgba(255, 255, 255, 0.4)',
  }) : null

  try {
    trajectoryLoading.value = true
    eventSourceClose()

    // 建立SSE连接
    eventSource.value = new EventSource(`${import.meta.env.VITE_WEB_BASE_API}/track/actual-time/sse?flights=${id}`)
    eventSource.value.onmessage = function (event) {
      // console.log('SSE数据:', JSON.parse(event.data))
      const obj = JSON.parse(event.data)
      // debugger
      obj.forEach(item => {
        mapApi.modelMove.realTImeMoveModel(item.id, item.coordinates, 0)
      }
      )

    }
  } catch (error) {
    console.error('获取轨迹数据失败:', error)
    ElMessage.error('获取轨迹数据失败')
  } finally {
    trajectoryLoading.value = false
    loadingInstance?.close()
  }
}

// 监听选中架次变化
watch(() => dRecordIds.value, (newVal, oldVal) => {
  // if (!oldVal.length) return

  // const removedIds = oldVal.filter(id => !newVal.includes(id))
  // if (removedIds.includes(focusedId.value)) {
  //   focusedId.value = null
  // }

  // // 清理移除的架次资源
  // removedIds.forEach(id => {
  //   activeFlightData.value = activeFlightData.value.filter(flight => flight.drecordId !== id)

  //   if (timerMap.value.has(id)) {
  //     clearInterval(timerMap.value.get(id))
  //     timerMap.value.delete(id)
  //   }
  // })
}, { deep: true })

// 生命周期钩子
onMounted(() => {
  mapStores.setMapType(['layerRealTime'])
  getTodaysFlights()
})

// 组件销毁前清理资源
onBeforeUnmount(() => {
  activeFlightData.value = []
  timerMap.value.forEach(clearInterval)
  timerMap.value.clear()
  focusedId.value = null
  eventSourceClose()
})

// 监听飞行数据事件
eventBus.subscribe('dispatchFlightData', (e) => {
  const { data, coordinates } = e.detail

  // 更新活动架次数据
  activeFlightData.value = [{
    ...data,
    currentTime: moment(new Date()).format("MM-DD HH:mm:ss"),
    status: '飞行中',
    airplaneOrder: flightList.value.find(opt => opt.value === data.drecordId)?.label || ''
  }]

  // 显示覆盖物
  olService.showOverLay(generateOverlayContent(data), coordinates)
})


/**
 * 清除所有实时轨迹
 */
const clearRealTimeAll = () => {
  eventSourceClose()
  // 清除所有轨迹
  dRecordIds.value.map(item => {
    mapApi.modelMove.removeRealModel(item)
  })
  dRecordIds.value = []
}

// 导出方法供父组件使用
defineExpose({
  getTodaysFlights,
  clearRealTimeAll,
})
</script>

<style lang="scss" scoped>
.realTime {
  height: 100%;
  padding: 12px;
  overflow-y: auto;
}

.flight-item {
  height: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  margin-right: 0;
  transition: transform 0.2s ease;

  &:hover {
    transform: translateX(2px);
  }

  :deep(.el-checkbox) {
    display: flex;
    margin: 0;
    padding: 0;
    height: auto;
  }

  :deep(.el-checkbox__input) {
    margin: 12px 0 0 10px;
  }

  :deep(.el-checkbox__label) {
    padding: 0;
    flex: 1;
  }
}

.flight-content {
  position: relative;
  margin-left: 10px;
  padding: 10px 12px;
  background: rgba(246, 248, 252, 0.7);
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid rgba(103, 194, 58, 0.1);

  &:hover {
    background: rgba(238, 241, 248, 0.9);
    border-color: rgba(103, 194, 58, 0.2);
    box-shadow: 0 4px 12px rgba(103, 194, 58, 0.08);
  }
}

.flight-id {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 6px;
  padding-right: 70px;
  line-height: 1.3;
}

.flight-info {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
  line-height: 1.3;

  span {
    display: flex;
    align-items: center;
  }
}

.flight-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  font-size: 12px;
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
  border-radius: 6px;
  white-space: nowrap;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;

  &:hover {
    background: rgba(103, 194, 58, 0.15);
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
  opacity: 0.7;
  transition: opacity 0.3s ease;

  &:hover {
    opacity: 0.9;
  }

  i {
    font-size: 32px;
    margin-bottom: 12px;
    color: #67c23a;
    opacity: 0.5;
  }

  span {
    font-size: 14px;
  }
}

.overlay-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px;
  min-width: 240px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.18);

  .overlay-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(103, 194, 58, 0.15);
  }

  .status-tag {
    background: rgba(103, 194, 58, 0.15);
    color: #67c23a;
    padding: 3px 10px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
    letter-spacing: 0.3px;
  }

  .flight-number {
    color: #2c3e50;
    font-size: 14px;
    font-weight: 600;
    letter-spacing: 0.3px;
  }

  .overlay-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
  }

  .grid-item {
    .label {
      color: #909399;
      font-size: 12px;
      margin-bottom: 4px;
      letter-spacing: 0.3px;
    }

    .value {
      color: #2c3e50;
      font-size: 14px;
      font-weight: 500;
      letter-spacing: 0.3px;

      .unit {
        font-size: 12px;
        color: #909399;
        margin-left: 4px;
        font-weight: normal;
      }
    }
  }
}
</style>